package com.yonyou.iuap.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.yonyou.iuap.base.vo.FastDfsMsgVO;
import com.yonyou.iuap.pub.JsonUtils;
import com.yonyou.iuap.shell.entity.exp.ShellFileUpPoJo;
import com.yonyou.iuap.shell.pub.ResultDto;
import com.yonyou.iuap.shell.service.intf.IKmFileManagerService;

@Controller
@RequestMapping("/file-dfs")
public class KmFileContronller {
	
	@Autowired
	private IKmFileManagerService iKmFileManagerService;
	@RequestMapping("/uploadFile")
	@ResponseBody
	public Object uploadFile(@RequestBody String picHref,HttpServletRequest request,HttpServletResponse response){
		ResultDto rsDto = new ResultDto();
		 ShellFileUpPoJo filepojo = new ShellFileUpPoJo();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("Filedata");
        InputStream is= null;
        int width = 0; // 原始图片宽
        int height = 0; // 原始图片高
        try {
        	byte[] bytes = getFileBuffer(multipartFile.getInputStream(),multipartFile.getSize());
            is = new ByteArrayInputStream(bytes);
            BufferedImage bufimg = ImageIO.read(is);
            // 只有图片才获取高宽
            if (bufimg != null) {
                width = bufimg.getWidth();
                height = bufimg.getHeight();
                filepojo.setWidth(String.valueOf(width));
                filepojo.setHeight(String.valueOf(height));
            }
            String originalFilename = multipartFile.getOriginalFilename(); // 文件全名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1,originalFilename.length()); // 后缀
            filepojo.setFile_name(originalFilename.substring(0,originalFilename.lastIndexOf(".")));
            filepojo.setFile_hz(suffix);
            FastDfsMsgVO msgvo =iKmFileManagerService.uploadFile(bytes,filepojo);
            msgvo.setFile_name(filepojo.getFile_name());
            rsDto.setStatus(msgvo.getStatus());
    		rsDto.setMessage(msgvo.getMsg());
    		rsDto.setData(msgvo);
            if(is!=null){
            	is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
            	if(is!=null){
            		is.close();
            	}
			} catch (IOException e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
			}
            rsDto.setStatus(-1);
            rsDto.setMessage(e.getMessage());
        }
		
		return rsDto;
	}
	private  byte[] getFileBuffer(InputStream inStream, long fileLength) throws IOException {

        byte[] buffer = new byte[256 * 1024];
        byte[] fileBuffer = new byte[(int) fileLength];

        int count = 0;
        int length = 0;

        while ((length = inStream.read(buffer)) != -1) {
            for (int i = 0; i < length; ++i) {
                fileBuffer[count + i] = buffer[i];
            }
            count += length;
        }
        return fileBuffer;
    }
	
	@RequestMapping("/delFile")
	@ResponseBody
	public String deleteFile(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response){
		ResultDto rsDto = new ResultDto();
		FastDfsMsgVO msgvo = iKmFileManagerService.deleteFile(map);
		rsDto.setStatus(msgvo.getStatus());
		rsDto.setMessage(msgvo.getMsg());
		return JsonUtils.toJsonStr(rsDto);
	}
	@RequestMapping("/downloadFile")
	@ResponseBody
	public String  downloadFile(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response){
		ResultDto rsDto = new ResultDto();
		//Map<String,String> map = new HashMap<String, String>();
		map.put("pk_user", "admin");
		map.put("pk_att", "93c4b126-12b1-41cb-bb5b-b3a08885a5f8");
		 FastDfsMsgVO msgvo = iKmFileManagerService.downFile(map);
		 if(msgvo.getB_file()==null || msgvo.getB_file().length==0){
			 rsDto.setStatus(-1);
			 rsDto.setMessage("未获取到需要下载的文件!");
		 }else{
			 OutputStream out = null;
			 try {
//				 File file = new File("shell_down/");
//				 if(!file.exists()){
//					 file.mkdirs();
//				 }
//				 BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
				 String filename = URLEncoder.encode(StringUtils.isEmpty(msgvo.getFile_name())?"unknown":msgvo.getFile_name());
				 String filekz = (StringUtils.isEmpty(msgvo.getFile_hz())?"":msgvo.getFile_hz());
	        	 response.reset();
	    		 response.setContentType("application/x-msdownloadoctet-stream;charset=utf-8");
	             response.addHeader("Content-Disposition", "attachment;fileName=" + filename+ "." +filekz);
				 out = response.getOutputStream();
				 out.write(msgvo.getB_file());
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				rsDto.setStatus(-1);
				rsDto.setMessage("【下载失败：】"+e.getMessage());
			}finally{
				if(out!=null){
					try {
						out.close();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
			} 
		 }
         return JsonUtils.toJsonStr(rsDto);
	}
}
